//
//  TFCreationNoticesView.m
//  Tika
//
//  Created by tikeios_002 on 2024/5/31.
//

#import "TFCreationNoticesView.h"
#import "TFCreationNoticesCell.h"
static NSString * cellId = @"cell";

@interface TFCreationNoticesView ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *noticeTable;

@property (strong, nonatomic)NSIndexPath * noticeIndex;
@property (nonatomic, assign) BOOL noticesNowScroll;
@property (nonatomic, assign) NSInteger max;
@property (strong, nonatomic) UIViewPropertyAnimator *animator;
@property (nonatomic, copy) dispatch_block_t delayedBlock;
@property (nonatomic, assign) CGFloat startY;
@end
@implementation TFCreationNoticesView

- (void)dealloc {
    [self cancelAnimator];
    [self cancelAfter];
}

- (void)showOldAddNavViewToMainOldView1{
    UIView * oldBgSS = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    oldBgSS.clipsToBounds = YES;
    [self addSubview:oldBgSS];
    
    UIButton * sendBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreen_W-75, kStatusBarHeight+10, 60, 46)];
    sendBtn.layer.cornerRadius = 3;
    sendBtn.backgroundColor = [UIColor whiteColor];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:ColorHex(@"#333333") forState:UIControlStateNormal];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [sendBtn addTarget:self action:@selector(sendTap) forControlEvents:UIControlEventTouchUpInside];
    [oldBgSS addSubview:sendBtn];
    
    UIView * sendBg = [[UIView alloc]initWithFrame:CGRectMake(15, kStatusBarHeight+66, KScreen_W-30, (KScreen_H-KSafeAreaBottomHeight-25-(kStatusBarHeight+66))/2)];
    sendBg.backgroundColor = [UIColor whiteColor];
    sendBg.layer.cornerRadius = 3;
    [oldBgSS addSubview:sendBg];
    
    UILabel * sendTip = [[UILabel alloc]initWithFrame:CGRectMake(0, (sendBg.frame.size.height-40)/2, sendBg.frame.size.width, 40)];
    sendTip.text = @"发送区";
    sendTip.textColor = ColorHex(@"#f0f0f0");
    sendTip.textAlignment = NSTextAlignmentCenter;
    sendTip.font = [UIFont systemFontOfSize:28];
    [sendBg addSubview:sendTip];
}
- (void)awakeFromNib {
    [super awakeFromNib];
    self.backgroundColor = [UIColor clearColor];
    [self.noticeTable registerNib:[UINib nibWithNibName:@"TFCreationNoticesCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:cellId];
    self.noticeTable.estimatedRowHeight = 0;
    self.noticeTable.estimatedSectionFooterHeight = 0;
    self.noticeTable.estimatedSectionHeaderHeight = 0;
    self.noticeTable.delegate = self;
    self.noticeTable.dataSource = self;

//    UIPanGestureRecognizer *pan = self.noticeTable.panGestureRecognizer;
//    [pan addTarget:self action:@selector(dragRefresh:)];

    _max = 200;
}


- (void)cancelAfter {
    if (self.delayedBlock != nil) {
        // 在需要的时候取消延迟任务
        dispatch_block_cancel(self.delayedBlock);
        self.delayedBlock = nil;
    }
}

- (void)cancelAnimator {
    if (self.animator != nil) {
        [self.animator stopAnimation:YES];
        self.animator = nil;
    }
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{

}
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view{

}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

    if (_cellDatas.count == 1) return;
    self.noticesNowScroll = YES;
    [self cancelAnimator];
    [self cancelAfter];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (_cellDatas.count == 1) return;
    int row = scrollView.contentOffset.y/self.frame.size.height;
    if (row >= 0 && row < [self.noticeTable numberOfRowsInSection:0]) {
        self.noticeIndex = [NSIndexPath indexPathForRow:row inSection:0];
        [self.noticeTable scrollToRowAtIndexPath:self.noticeIndex
                                atScrollPosition:UITableViewScrollPositionNone animated:NO];
    }
    [self noticeScroll];
    self.noticesNowScroll = NO;
}

-(void) noticeScroll{
    if ( self.noticeIndex != nil && [self.noticeTable numberOfRowsInSection:0] > self.noticeIndex.row) {
        [self.noticeTable scrollToRowAtIndexPath:self.noticeIndex
                                atScrollPosition:UITableViewScrollPositionTop animated:YES];
        KWeakSelf
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            TFCreationNoticesCell * cell = nil;
            CGFloat w = 0;
            cell = (TFCreationNoticesCell *)[weakSelf.noticeTable cellForRowAtIndexPath:weakSelf.noticeIndex];
            if (cell == nil) {
                [weakSelf createAfter];
                return;
            }
            CGRect rect = cell.contentLabel.frame;
            rect.origin.x = 0;
            cell.contentLabel.frame = rect;
            w = cell.contentLabel.frame.size.width-cell.contentLabelView.frame.size.width;
            if(w > 0){
                CGFloat time = w/10.0;
                if (time < 0.22) {
                    time = 0.22;
                }
                [weakSelf cancelAnimator];
                weakSelf.animator = [UIViewPropertyAnimator runningPropertyAnimatorWithDuration:time*0.22 delay:0.5 options:UIViewAnimationOptionCurveLinear animations:^{
                    CGRect _aRect = cell.contentLabel.frame;
                    _aRect.origin.x = -w;
                    cell.contentLabel.frame = _aRect;//CGRectMake(-w, 0, cell.contentLabel.frame.size.width, 40);
                } completion:^(UIViewAnimatingPosition finalPosition) {
                    if (finalPosition == UIViewAnimatingPositionEnd) {
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            if(cell){
                                CGRect _iRect = cell.contentLabel.frame;//CGRectMake(0, 0, cell.contentLabel.frame.size.width, 40);
                                _iRect.origin.x = 0;
                                cell.contentLabel.frame = _iRect;
                            }
                            if(weakSelf.noticesNowScroll){
                                return;
                            }
                            NSIndexPath *indexPath = [weakSelf.noticeTable indexPathForCell:cell];
                            if(indexPath.row != weakSelf.noticeIndex.row){
                                return;
                            }
                            if (weakSelf.cellDatas.count == 1) { [weakSelf noticeScroll]; return;}
                            weakSelf.noticeIndex = [NSIndexPath indexPathForRow:weakSelf.noticeIndex.row+1 inSection:0];
                            if(weakSelf.noticeIndex.row >= weakSelf.cellDatas.count*weakSelf.max){
                                weakSelf.noticeIndex = [NSIndexPath indexPathForRow:weakSelf.cellDatas.count*weakSelf.max / 2 inSection:0];
                            }
                            if ( weakSelf.noticeIndex != nil && [weakSelf.noticeTable numberOfRowsInSection:0] > weakSelf.noticeIndex.row) {
                                [weakSelf.noticeTable scrollToRowAtIndexPath:weakSelf.noticeIndex
                                                            atScrollPosition:UITableViewScrollPositionTop animated:YES];
                            }
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                if(weakSelf.noticesNowScroll){
                                    return;
                                }
                                [weakSelf noticeScroll];
                            });
                        });
                    }
                }];
            } else {
                if (weakSelf.cellDatas.count == 1) {
                    return;
                }
                weakSelf.noticeIndex = [NSIndexPath indexPathForRow:weakSelf.noticeIndex.row+1 inSection:0];
                if(weakSelf.noticeIndex.row >= weakSelf.cellDatas.count*weakSelf.max){
                    weakSelf.noticeIndex = [NSIndexPath indexPathForRow:weakSelf.cellDatas.count*weakSelf.max / 2 inSection:0];
                }
                [weakSelf createAfter];
            }
        });
        
    }
}

- (void)createAfter {
    [self cancelAfter];
    KWeakSelf
    self.delayedBlock = dispatch_block_create(0, ^{
        // 延迟任务代码
        [weakSelf noticeScroll];
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), self.delayedBlock);
}

#pragma mark - <UITableViewDelegate,UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.cellDatas.count > 1)
        return self.cellDatas.count*_max;
    return self.cellDatas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TFCreationNoticesCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (self.cellDatas.count > 1) {
        if (indexPath.row%self.cellDatas.count < self.cellDatas.count) {
            NSDictionary *tempData = self.cellDatas[indexPath.row%self.cellDatas.count];
            cell.contentLabel.text = tempData[@"contents"];

            CGFloat w = [Tools sizeForText:cell.contentLabel.text withFont:cell.contentLabel.font withSize:CGSizeMake(MAXFLOAT, 20)].width+3;
            cell.contentLabel.frame = CGRectMake(0, 0, w, self.frame.size.height);
        }
    } else {
        NSDictionary *tempData = self.cellDatas[indexPath.row];
        cell.contentLabel.text = tempData[@"contents"];
        CGFloat w = [Tools sizeForText:cell.contentLabel.text withFont:cell.contentLabel.font withSize:CGSizeMake(MAXFLOAT, 20)].width+3;
        cell.contentLabel.frame = CGRectMake(0, 0, w, self.frame.size.height);
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.noticeHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.CreatorCenterNoticesActionBlock && self.cellDatas.count == 1) {
        NSString *contents = [self.cellDatas[indexPath.row] objectForKey:@"contents"];
        NSString *titles = [self.cellDatas[indexPath.row] objectForKey:@"titles"];
        self.CreatorCenterNoticesActionBlock(0, titles,contents);
        return;
    }
    if (self.CreatorCenterNoticesActionBlock && indexPath.row%self.cellDatas.count < self.cellDatas.count) {
        NSString *contents = [self.cellDatas[indexPath.row%self.cellDatas.count] objectForKey:@"contents"];
        NSString *titles = [self.cellDatas[indexPath.row%self.cellDatas.count] objectForKey:@"titles"];
        self.CreatorCenterNoticesActionBlock(0, titles,contents);
    }
}

- (void)setCellDatas:(NSArray *)cellDatas{
    _cellDatas = cellDatas;
    if(self.cellDatas){
        [self.noticeTable reloadData];
        if (self.cellDatas.count > 1) {
            KWeakSelf
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //获取到需要跳转位置的行数
                weakSelf.noticeIndex = [NSIndexPath indexPathForRow:weakSelf.cellDatas.count*weakSelf.max / 2 inSection:0];
                //滚动到其相应的位置
                if (weakSelf.noticeIndex != nil && [weakSelf.noticeTable numberOfRowsInSection:0] > weakSelf.noticeIndex.row) {
                    [weakSelf.noticeTable scrollToRowAtIndexPath:weakSelf.noticeIndex
                                                atScrollPosition:UITableViewScrollPositionNone animated:NO];
                }
                [weakSelf noticeScroll];
            });
        } else {
            if ([self.noticeTable numberOfRowsInSection:0] > 0) {
                self.noticeIndex = [NSIndexPath indexPathForRow:0 inSection:0];
            }
            [self noticeScroll];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if(decelerate) return;
    [self scrollViewDidEndDecelerating:scrollView];
}
- (void)scrollViewDidEndDragging:(UITableView *)tableview{
    [self.noticeTable scrollToRowAtIndexPath:[tableview indexPathForRowAtPoint:CGPointMake(tableview.contentOffset.x, tableview.contentOffset.y+self.noticeHeight/2)] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
#pragma mark -2.0.4 dragRefresh: 下拉刷新
- (void)dragRefresh:(UIPanGestureRecognizer *)pan {

    switch (pan.state) {
        case UIGestureRecognizerStateBegan: {
            [self cancelAfter];
            self.startY = [pan locationInView:self].y;
        }
            break;
        case UIGestureRecognizerStateChanged: {
            CGFloat y = [pan locationInView:self].y;
            NSLog(@"%f",y);
            if(y - self.startY > self.frame.size.height || y - self.startY < -self.frame.size.height){
                pan.enabled = NO;
                pan.enabled = YES;
                [self createAfter];
            }
        }
            break;
        case UIGestureRecognizerStateEnded: {
            [self createAfter];
        }
            break;
        default:
            break;
    }
}
@end
